<template>
  <div class="m-form-item">
    <div class="m-form-item_title">
      <span class="title-required" v-if="required || rule.length > 0">* </span>
      <span>{{ label }}</span>
    </div>
    <div class="m-form-item_content">
      <slot ref="item"></slot>
    </div>
    <div v-if="showError && rule.length > 0" class="valid-error">
      {{ rule[0].message || "请完善" }}
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { isNotEmpty } from "@/utils/validate";

const props = defineProps({
  label: {
    type: String,
    default: ""
  },
  rule: {
    type: Array,
    default: () => {
      return [];
    }
  },
  prop: {
    type: String,
    default: ""
  },
  model: {
    type: Object,
    default: () => {
      return {};
    }
  },
  required: {
    type: Boolean,
    default: false
  }
});

const showError = ref(false);

const validate = call => {
  if (props.rule.length) {
    if (props.rule[0].type === "array") {
      showError.value = Array.isArray(props.model[props.prop] && props.model[props.prop].length);
    } else {
      showError.value = !isNotEmpty(props.model[props.prop]);
    }
  }
  if (call) {
    call(!showError.value);
  }
};
</script>

<style lang="scss" scoped>
.m-form-item {
  position: relative;
  padding: 10px 10px 20px 10px;
  background: white;
  margin-bottom: 10px;
  & > div:first-child {
    margin-bottom: 8px;
    font-size: 1.2rem;
    color: #545456;
  }
  .title-required {
    color: #f56c6c;
  }
  .valid-error {
    color: #f56c6c;
    position: absolute;
    font-size: 0.85rem;
  }
}
</style>
